﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace LockDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var classA = new classA();
            LockTest test = new LockTest() { A = new List<string> { "1", "2", "3", "4", "2", "3", "4", "2", "3", "4", "2", "3", "4", "2", "3", "4", "2", "3", "4", "2", "3", "4", "2", "3", "4", "2", "3", "4", "2", "3", "4" } };

            for (var i = 20; i > 0; i--)
            {
                //classA.testlock(test);
                //Task.Run(() => classA.testlock(test));
            }

            classA.testlock(test);
            Console.ReadLine();
        }
    }

    public class classA
    {
        public void testlock(LockTest i)
        {
            Console.WriteLine($"当前线程Id：{Thread.CurrentThread.ManagedThreadId}--锁之前");
            lock (this)
            {
                Console.WriteLine($"当前线程Id：{Thread.CurrentThread.ManagedThreadId}--锁住了，输出count:{i.A.Count}-- 当前引用地址：{this}");
                if (i.A.Count > 1)
                {
                    //Thread.Sleep(5000);
                    i.A.RemoveAt(0);
                    //testlock(i);
                    Task.Run(()=>testlock(i)).Wait();
                }
                //Thread.Sleep(1000);
            }
            //Thread.Sleep(1000);
            //i.A[1] = Thread.CurrentThread.ManagedThreadId.ToString();
            Console.WriteLine($"当前线程Id：{Thread.CurrentThread.ManagedThreadId}--马上解锁");
        }        
    }

    public class LockTest
    {
        public List<string> A;
    }

    public class LockExcute
    {
        public void Test2()
        {
            for (var i = 20; i > 0; i--)
            {
                var task = new Task(Test);
                task.Start();
            }

        }

        public void Test()
        {
            var test = new classA();
            test.testlock(new LockTest { A = new List<string> { "1", "2", "3" } });
        }
    }
}
